/**
 * 
 */
package de.fsujena.chat_pi.server;

import java.io.*;

import de.fsujena.chat_pi.user.UserManager;

/**
 * Server implementation. It holds user and room manager and starts a network listener on 
 * a specific port. It also offers methods to display messages for the server.
 * 
 * @author Erik Hebestreit
 */
public class Server {
	
	UserManager userManager;
	NetworkListener networkListener;
	
	private int port = 3141;

	/**
	 * @param args
	 * @throws IOException 
	 */
	public static void main(String[] args) {
		// create a new instance of the server object
		new Server().startServer(args);
	}
	
	public void startServer(String[] args) {
		// initialize user manager
		userManager = new UserManager();
		
		startNetworkListener(args);
	}
	
	public void startNetworkListener(String[] args) {
		// TODO specify port by input argument if given,
		
		
		try {
			// launch network listener on specific port
			networkListener = new NetworkListener(port,this);
			
			/*
			 *  start network listener thread which handles login, registration and
			 *  listens for conventional messages
			 */
			networkListener.start();
			
			postInfo(String.format("server started on port %d",port));
		} catch (IOException e) {e.printStackTrace();}
	}
	
	/**
	 * Handler to post standard info messages for the server.
	 * 
	 * @param message info message to be posted
	 */
	public void postInfo(String message) {
		System.out.println("INFO>> " + message);
	}
	
	/**
	 * Handler to post warnings for the server.
	 * 
	 * @param message warning to be posted
	 */
	public void postWarning(String message) {
		System.out.println("WARNING>> " + message);
	}
	
	/**
	 * Handler to post errors for the server.
	 * 
	 * @param message error to be posted
	 */
	public void postError(String message) {
		System.err.println("ERROR>> " + message);
	}
	
	/**
	 * Handler to post text messages for the server.
	 * 
	 * @param message text to be posted
	 */
	public void postTextMessage(String user, String message) {
		System.out.println(user.toUpperCase() + ">> " + message);
	}
	
	/**
	 * @param port port number where the server should listen
	 * @return <b>true</b> if port was set successfully,
	 * <b>false</b> if port number exceeded possible port numbers
	 */
	public boolean setPort(int port) {
		if (port > 1024 && port <= 65535) {
			this.port = port;
			return true;
		} else {
			return false;
		}
	}
	
	/**
	 * @return port number where the server is listening
	 */
	public int getPort() {
		return this.port;
	}

}
